package netty.rpc.framework.core.netty.consumer;

import io.netty.channel.Channel;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import netty.rpc.framework.core.netty.factory.SingletonFactory;
import netty.rpc.framework.core.netty.transport.client.NettyCilent;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author guiyiqiao
 * @date 2020/12/11
 */
@Slf4j
public class ChannelProvider {

    private NettyCilent nettyCilent;

    private  Map<InetSocketAddress, Channel> serviceChannel ;

    public ChannelProvider() {
        this.serviceChannel = new ConcurrentHashMap<>();
        nettyCilent = SingletonFactory.getInstance(NettyCilent.class);
    }

    /**
     * 获取netty的通道，若不存在则新建一个
     * @param channelAddress
     * @return
     */
    public Channel getChannel(@NonNull InetSocketAddress channelAddress){
        Channel channel = serviceChannel.get(channelAddress);
        if(channel == null || !channel.isActive()){
            serviceChannel.remove(channelAddress);
        }else {
            return channel;
        }
        log.info("连接provider");
        Channel connect = nettyCilent.connect(channelAddress);
        putChannel(channelAddress,connect);
        return connect;
    }

    public void putChannel(@NonNull InetSocketAddress address,@NonNull Channel channel){
        serviceChannel.put(address,channel);
    }
}
